<template>
  <Page name="修改密码" :back="from" @back='back'>
    <div class="page-auth-content">
      <div class="tip fx fx-vc" v-if="showTip">
        <i class="ic ic-tip-yellow mr12"></i>
        <p class="flex">为了您的账号安全，首次登录请修改登录密码</p>
        <div class="close-wrap" @click="showTip = false">
          <i class="close"></i>
        </div>
      </div>
      <form class="auth-wrap" @keypress.enter="submit" onsubmit="return false">
          <div class="form-item fx fx-center">
            <span class="form-label">乐马号</span>
            <Input class="flex" placeholder="请输入乐马号" v-model="username" />
          </div>
          <div class="form-item fx fx-center">
            <span class="form-label">新密码</span>
            <Password class="flex" placeholder="6-30位含大小写字母数字组合" v-model="pwd" />
          </div>
          <div class="form-item fx fx-center">
            <span class="form-label">再次确认</span>
            <Password class="flex" placeholder="6-30位含大小写字母数字组合" v-model="repwd" />
          </div>
          <a class="btn btn-block btn-primary submit" :disabled="!valid_form" @click="submit($event)">提交</a>
      </form>
    </div>
  </Page>
</template>

<script>
import Page from '~/components/page';
import Input from '~/components/Input';
import Password from '~/components/Password';

export default {
  components:{
    Password,
    Input,
    Page
  },
  asyncData({redirect,query}){
    let data = sessionStorage.getItem('recheck_user');
    let user;
    if(data){
      try{
        user = JSON.parse(data);
      }catch(e){
        console.error(e);
      }
    }
    if(!user){
      console.log('go login')
      redirect('/login')
      return false;
    }
    return {
      originType: query.originType,
      origin: query.origin,
      New: query.isNew,
      type:query.type,
      user,
      username:user.username,
      from:!!query.from || false,
    }
  },
  data(){
    return {
      pwd:'',
      repwd:'',
      posting:false,
      showTip:true,
    }
  },
  computed: {
    valid_form(){
      let flag = true;
      flag = !!String(this.username).trim() && !!String(this.pwd).trim() && !!String(this.repwd).trim();
      if(flag){
        if(this.pwd !== this.repwd){
          flag = false;
        }
      }
      return  flag;
    }
  },
  mounted(){
    this.$emit('changeBg','#fff');
  },
  destroyed(){
    sessionStorage.removeItem('recheck_user')
  },
  methods: {
    checkPassword(value){
      var lv = 0;var val = value;
      if (val.match(/[A-Z]/g)) {
        lv++;
      }
      if (val.match(/[a-z]/g)) {
        lv++;
      }
      if (val.match(/[0-9]/g)) {
        lv++;
      }

      if (lv < 3 || value.length < 6 || value.length >30) {
        this.$toast('密码格式不正确');
        return false;
      } else {
        return true;
      }
    },
    recheckPassword(){
      if(this.pwd !== this.repwd){
        this.$toast('两次密码不一致');
        return false;
      }
      return true;
    },
    async submit(e){
      if(this.posting || !this.valid_form || !this.checkPassword(this.pwd) || !this.recheckPassword()) return false;
      try{
        let { data:rs } = await this.$axios.post('?ct=api&ac=first_login_reset_pwd',{
          username:this.username,
          pwd:this.pwd,
          token:this.user.token,
          uid:this.user.uid,
        })

        if(rs.code === 0){
          const { data } = rs;
          this.$store.commit("SET_UID",this.user.uid );
          this.$store.commit("SET_TOKEN",this.user.token);
          //如果是注册来的，且用户列表大于1，需要跳到用户选择页面
          if(this.user.group_labels.length>1){
            this.$router.push({name:'login-list',
              params:{
                list:this.user.group_labels,
                token:this.user.token,
                isNew: this.isNew,
                type: this.type
              },
              query: {
                origin:this.origin,
                originType:this.originType,
              }
            })
            return false;
          }else if(!this.user.user_code && !this.user.phone){//如果用户注册过来的清空下，user的数据是不完整的，需要获取一次用户信息接口
            try {
              let param = {
                uid:this.user.uid,
                pid:this.user.group_labels[0].uid,
                token:this.user.token,
                origin:this.origin,
                originType:this.originType,
              }

              let { data: urs } = await this.$axios.post('?ct=api&ac=select_member',param);
              if(urs.code == 0){
                const udata = urs.data;
                this.$store.commit("SET_UID",udata.uid);
                this.$store.commit("SET_TOKEN",udata.token);
                this.$store.commit("SET_USER",udata);
              }else{
                this.$toast(urs.msg);
              }
            }catch(e){
              this.$toast('获取用户信息失败');
              return false;
            }

          }else{
            this.$store.commit("SET_USER",this.user);
          }
          this.$toast('修改成功',1000).then(()=>{
            if(data.flow_status == 0 && this.origin == 4) {
              this.$router.push({name:'complete_info'});
            } else {
              this.$router.replace('/');
            }
          })
        }else {
          this.$toast(rs.msg);
          this.posting = false;
        }
      }catch(e){
        this.$error(e);
        this.posting = false;
      }

    },
    back(){//目前只有来自注册页面的才会处理，返回直接跳去登录页
      this.$router.replace({
        name:'login',
        query:{origin:this.origin, originType:this.originType},
      });
    }
  }
}
</script>

<style lang="less" scoped>
  @import url("~assets/less/module/auth.less");
  .submit {
    margin-top:60px;
  }
</style>


